const express = require('express');
const cors = require('cors');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const userRoutes = require('./routes/userRoutes');
const { testConnection } = require('./config/db');
const UserModel = require('./models/userModel');
require('dotenv').config();

const app = express();
const port = 3000;

// 微信小程序配置
const APPID = process.env.WX_APPID;
const SECRET = process.env.WX_SECRET;

app.use(cors());
app.use(express.json());

// 初始化数据库
const initDatabase = async () => {
  try {
    await testConnection();
    await UserModel.createTable();
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1);
  }
};

// 微信登录接口
app.post('/api/login', async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少登录码' 
      });
    }

    // 调用微信登录凭证校验接口
    const wxLoginUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
    
    const response = await axios.get(wxLoginUrl);
    const { openid, session_key } = response.data;

    if (!openid) {
      return res.status(401).json({
        success: false,
        message: '微信登录失败'
      });
    }

    // 生成JWT token
    const token = jwt.sign(
      { openid },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      message: '登录成功',
      data: { token }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 用户相关路由
app.use('/api/user', userRoutes);

// 测试接口
app.get('/api/test', (req, res) => {
  res.json({
    success: true,
    message: '服务器运行正常'
  });
});

// 启动服务器
initDatabase().then(() => {
  app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
  });
}); 